<template>
  <div :class="$style.msgSend">
    <ContentWrap>
      <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
        <el-form-item prop="phone" label="手机号码">
          <el-input v-model.trim="formData.phone" placeholder="请输入11位标准手机号码" clearable style="width:153px;" />
          <span :class="$style.tip" style="padding-left:5px;">温馨提示：仅限发送短信给一个标准手机号码</span>
          <!-- <span :class="$style.tip">必须为11位标准手机号</span> -->
        </el-form-item>
        <el-form-item prop="template" label="短信模板">
          <el-select v-model="formData.template" placeholder="请选择短信模板" remote :remote-method="postPage" clearable filterable @change="changeHandle">
            <el-option v-for="(tl,i) in templateList" :key="i" :label="tl.name" :value="tl.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="isTiming" label="是否定时发送">
          <el-select v-model="formData.isTiming" placeholder="请选择" clearable filterable>
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.isTiming===1" prop="sendDate" label="定时发送时间">
          <el-date-picker v-model="formData.sendDate" operator="<" :limite="new Date()" type="datetime" />
        </el-form-item>
        <el-form-item prop="content" label="短信内容">
          <el-input v-model="formData.content" type="textarea" :maxlength="150" tip :autosize="{minRows:3}" placeholder="短信内容" />
          <!-- <span class="input-tip">剩余{{ surplus }}字</span> -->
        </el-form-item>
        <el-form-item>
          <Button type="primary" :loading="loading" @click="submitClickHandle">发送</Button>
          <Button type="primary" @click="resetHandle">重置</Button>
        </el-form-item>
      </el-form>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import Button from '@/components/Button'
import { notEmpty, deepCopy } from '@/utils'
import { validatPhone } from '@/utils/validate'
import { postPage } from '@/api/smsOrEmailTemp'
import { postSmsCreat } from '@/api/sms'
import { parseTime, filtersRaw, pageRequsetBody } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  name: 'SMSSend',
  components: {
    ContentWrap,
    Button
  },
  data() {
    // 验证短信内容
    const validatorContent = (r, v, c) => {
      if (v.length > this.maxNum) {
        c(new Error(`最多输入${this.maxNum}个字符`))
      } else {
        c()
      }
    }
    // 验证发送时间
    const validatorTiming = (r, v, c) => {
      if (this.formData.isTiming === 1) {
        if (notEmpty(v)) {
          const t = v.getTime() - 30 * 60 * 1000
          const n = new Date().getTime()
          if (t < n) {
            c(new Error('定时发送时间距现在不能小于半小时！'))
          } else {
            c()
          }
        } else {
          c(new Error('请选择发送时间'))
        }
      } else {
        c()
      }
    }
    // 验证手机号
    const validatorPhone = (r, v, c) => {
      validatPhone(v) ? c() : c(new Error('请检查输入的手机号是否正确'))
    }
    return {
      formData: {
        phone: '',
        template: '',
        isTiming: 0,
        sendDate: new Date(new Date().getTime() + 35 * 60000),
        content: ''
      },
      formRules: {
        phone: [
          { required: true, message: '请输入11位手机号码', trigger: 'change' },
          { requerid: true, validator: validatorPhone, trigger: 'change' }
        ],
        // template: [{ required: true, message: '请选择短信模板', trigger: 'change' }],
        isTiming: [{ required: false, message: '请选择是否定时发送', trigger: 'change' }],
        sendDate: [
          { required: true, type: 'date', validator: validatorTiming, trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入短信内容', trigger: 'change' },
          { validator: validatorContent, trigger: 'change' }
        ]
      },
      // 最大输入字数
      maxNum: 150,
      loading: false,
      templateList: [] // 短信模板列表
      // 禁止选择日期
      // pickerOptions: {
      //   disabledDate(date) {
      //     const now = new Date()
      //     const y = now.getFullYear()
      //     const m = now.getMonth() + 1
      //     const d = now.getDate()
      //     return date.getTime() < new Date(`${y}-${m}-${d}`).getTime()
      //   }
      // }
    }
  },
  computed: {
    surplus() {
      const t = this.maxNum - this.formData.content.length
      return t >= 0 ? t : 0
    },
    ...mapGetters(['groupList'])
  },
  created() {
    this.getCallTel()
    // 获取模板数据
    this.postPage('')
    this.getContent()
  },
  methods: {
    // 如果query上带有content则填充到formData.content
    getContent() {
      const content = this.$route.query.content
      if (content) {
        this.$set(this.formData, 'content', content)
      }
    },
    // 发送
    submitClickHandle() {
      this.loading = true
      this.$refs.form.validate().then(() => {
        // return this.$msgbox({
        //   title: '发送',
        //   message: '确认发送短信？',
        //   showCancelButton: true,
        //   type: 'warning'
        // }).then(() => {
        const data = deepCopy(this.formData)
        if (data.isTiming === 1) {
          data.sendDate = parseTime(this.formData.sendDate, '{y}-{m}-{d} {h}:{i}:{s}')
        } else {
          delete data.sendDate
        }
        delete data.template
        // 判断是否是工单的短信
        const workOrderCode = this.$route.query.workOrderCode
        if (workOrderCode !== undefined && workOrderCode !== null && workOrderCode !== '') {
          data.businessType = 1
          data.businessCode = workOrderCode
        }
        return postSmsCreat(data).then(res => {
          this.$message.success('发送成功！')
          this.resetHandle()
          return res
        })
        // })
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取sms模板
    postPage(v) {
      const data = {
        filtersRaw: [
          filtersRaw('type', 1, '='),
          filtersRaw('name', v, 'like'),
          filtersRaw('enabled', 1, '='),
          filtersRaw('group', this.groupList.map(e => e.groupNo).join(','), 'in')
        ]
      }
      postPage(pageRequsetBody(data)).then(res => {
        this.templateList = res.data.records
      })
    },
    // 选择短信模板后，更新短信输入框内容
    changeHandle(id) {
      let t = Object.create(null)
      for (let i = 0; this.templateList.length > i; i++) {
        if (this.templateList[i].id === id) {
          t = this.templateList[i]
          break
        }
      }
      this.$set(this.formData, 'content', t.content || '')
    },
    // 如果是通过话务条过来的，则从url上获取数据
    getCallTel() {
      const { callTel } = this.$route.query
      if (callTel) {
        this.$set(this.formData, 'phone', callTel)
      }
    },
    // 重置把表单
    resetHandle() {
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang='scss' module>
.msgSend{
  .tip{
    color: #ff4949;
    font-size: 12px;
  }
}
</style>
